package com.technology.education.ui.common.goods

import android.text.InputType
import android.view.Gravity
import android.widget.ImageView
import androidx.core.os.bundleOf
import androidx.lifecycle.lifecycleScope
import com.angcyo.dsladapter.dslItem
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.view.OptionsPickerView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.technology.education.R
import com.technology.education.base.BaseRecyclerTopBarFragment
import com.technology.education.data.model.ProvinceModel
import com.technology.education.dslitem.ItemColumnTitleEdit
import com.technology.education.dslitem.ItemColumnTitleText
import com.technology.education.dslitem.ItemSingleButton
import com.technology.education.dslitem.ItemSingleText
import com.technology.education.ext.*
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.ext.parseState

/**
 *@author:create by BZY
 *Date: 2022/3/29 12
 */
class ConfirmGoodOrderFragment : BaseRecyclerTopBarFragment<ConfirmGoodOrderViewModel>() {
    override fun initViews() {
        setTitle("确定订单")
        arguments?.let {
            mViewModel.info = it.getParcelable("info")
        }
        lifecycleScope.launch {
            initJsonData()
        }
    }

    override fun lazyLoadData() {
        renderAdapter {
            dslItem(R.layout.item_goods_add) {
                itemBindOverride = { itemHolder, _, _, _ ->
                    itemHolder.tv(R.id.tv_name)?.text = mViewModel.info?.name
                    itemHolder.tv(R.id.tv_info)?.text = mViewModel.info?.description
                    itemHolder.tv(R.id.tv_score)?.text = "${mViewModel.info?.price}积分"
                    itemHolder.tv(R.id.tv_count)?.text = mViewModel.count.toString()
                    itemHolder.v<ImageView>(R.id.iv_goods)?.apply {
                        loadImage(mViewModel.info?.coverImage, this)
                    }
                    itemHolder.click(R.id.tv_minus) {
                        if (mViewModel.count < 1) {
                            mViewModel.count = 1
                        }
                        updateAdapterItem()
                    }
                    itemHolder.click(R.id.tv_add) {
                        mViewModel.count += 1
                        updateAdapterItem()
                    }
                }
            }
            dslItem(ItemSingleText("收货地址")) {
                style.isBold = true
                style.bottomPadding = 8
            }
            dslItem(ItemColumnTitleEdit("姓名:", tag = "name", hintStr = "收货人姓名")) {
                style.contentGravity = Gravity.LEFT
                style.lineHeight = 0
                style.topPadding = 8
            }
            dslItem(ItemColumnTitleEdit("电话:", tag = "phone", hintStr = "收货人手机号")) {
                style.contentGravity = Gravity.LEFT
                style.contentInputType = InputType.TYPE_CLASS_NUMBER
                style.lineHeight = 0
                style.topPadding = 8
            }
            dslItem(ItemColumnTitleText("地区:", tag = "address", hintStr = "选择省/市/区")) {
                style.contentGravity = Gravity.LEFT
                style.lineHeight = 0
                style.topPadding = 8
                itemClick = {
                    showPicker()
                }
            }
            dslItem(ItemColumnTitleEdit("详细地址:", tag = "detail", hintStr = "街道门牌、楼房间信息")) {
                style.contentGravity = Gravity.LEFT
                style.topPadding = 8
            }

            dslItem(ItemSingleButton("立即兑换")) {
                style.topPadding = 32
                itemClick = {
                    closeInput()
                    mViewModel.name = getItemText("name") ?: ""
                    mViewModel.phone = getItemText("phone") ?: ""
                    mViewModel.detail = getItemText("detail") ?: ""
                    mViewModel.commitData()
                }
            }
        }
    }

    override fun createObserver() {
        mViewModel.result.observe(this) {
            parseState(it, onSuccess = { it ->
                navigation(requireView(),R.id.action_confirmGoodOrderFragment_to_goodsOrderDetailFragment,
                    bundleOf("id" to it.id))
            }, onError = { err -> toast(err.errorMsg) })
        }
    }

    private var options1Items: List<String> = ArrayList()
    private val options2Items: ArrayList<ArrayList<String>> = ArrayList()
    private val options3Items: ArrayList<ArrayList<ArrayList<String>>> = ArrayList()

    private fun initJsonData() { //解析数据
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         */
        val jsonData: String =
            com.technology.education.ext.getJson("province.json") //获取assets目录下的json文件数据
        val jsonBean: ArrayList<ProvinceModel> = Gson().fromJson(
            jsonData,
            object : TypeToken<ArrayList<ProvinceModel>>() {}.type
        ) //用Gson 转成实体
        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */

        options1Items = jsonBean.map {
            it.name ?: ""
        }
        jsonBean.forEach {
            options2Items.add(it.city!!.map { city ->
                city.name ?: ""
            } as java.util.ArrayList<String>)
            val area: ArrayList<ArrayList<String>> = ArrayList()
            it.city!!.forEach { city ->
                city.area?.let { it1 -> area.add(it1 as java.util.ArrayList<String>) }
            }
            options3Items.add(area)
        }

    }


    private var picker: OptionsPickerView<String>? = null
    private fun showPicker() {
        closeInput()
        if (picker == null) {
            picker = OptionsPickerBuilder(
                requireContext()
            ) { options1, options2, options3, v ->
                mViewModel.province = options1Items[options1]
                mViewModel.city = options2Items[options1][options2]
                mViewModel.district = options3Items[options1][options2][options3]
                renderAdapter {
                    setItemText(
                        "address",
                        "${mViewModel.province} ${mViewModel.city} ${mViewModel.district}"
                    )
                }
            }.setTitleText("选择所在城市")
                .setTitleSize(16)
                .setContentTextSize(14)
                .build()
            picker!!.setPicker(
                options1Items,
                options2Items as List<List<String>>, options3Items as List<List<List<String>>>
            )
        }
        picker!!.show()
    }
}